// +----------------------------------------------------------------------
// | Manong.Cloud [ 领酷码农云 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.manong.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Author: 稻草人 <qinuoyun@qq.com>
// +----------------------------------------------------------------------
// | Member: 围棋 飘逸者 Loumt Silence24
// +----------------------------------------------------------------------


const beforeCreate = Symbol('beforeCreate');
const afterCreate = Symbol('afterCreate');

const beforeDelete = Symbol('beforeDelete');
const afterDelete = Symbol('afterDelete');

const beforeUpdate = Symbol('beforeUpdate');
const afterUpdate = Symbol('afterUpdate');

const beforeQuery = Symbol('beforeQuery');
const afterQuery = Symbol('afterQuery');

global.BasicController =  class BasicController {
    /**
     * 生命周期
     * @type {{}}
     */
    $lifecycle = {}

    /**
     * 初始化构造方法
     * @param  {[type]}   ctx  [description]
     * @param  {Function} next [description]
     * @return {[type]}        [description]
     */
    constructor(ctx, next) {
        //存储用户数据
        if (ctx) {
            this.state = this.__state__ = ctx.state;
        }
        this.__ctx__ = ctx;
        this.__ModelName__ = this.constructor.name.replace(/Controller/, "");
        this.initLifecycle();
    }

    /**
     * 自动化方法
     */
    actionAutomate(){

    }

    /**
     * 初始化生命周期
     */
    initLifecycle() {
        //创建生命周期函数
        this.lifecycleObject = {
            Create: {
                before: this.$lifecycle.beforeCreate || this.beforeCreate || this[beforeCreate],
                after: this.$lifecycle.afterCreate || this.afterCreate || this[afterCreate]
            },
            Delete: {
                before: this.$lifecycle.beforeDelete || this.beforeDelete || this[beforeDelete],
                after: this.$lifecycle.afterDelete || this.afterDelete || this[afterDelete]
            },
            Update: {
                before: this.$lifecycle.beforeUpdate || this.beforeUpdate || this[beforeUpdate],
                after: this.$lifecycle.afterUpdate || this.afterUpdate || this[afterUpdate]
            },
            Query: {
                before: this.$lifecycle.beforeQuery || this.beforeQuery || this[beforeQuery],
                after: this.$lifecycle.afterQuery || this.afterQuery || this[afterQuery]
            }
        }
    }


    /**
     * 生命周期函数-创建前
     */
    [beforeCreate](value) {
        return new Promise((resolve, reject) => {
            resolve(value);
        })
    }

    /**
     * 生命周期函数-创建后
     */
    [afterCreate](value) {
        return new Promise((resolve, reject) => {
            resolve(value);
        })
    }

    /**
     * 生命周期函数-删除前
     */
    [beforeDelete](value) {
        return new Promise((resolve, reject) => {
            resolve(value);
        })
    }

    /**
     * 生命周期函数-删除后
     */
    [afterDelete](value) {
        return new Promise((resolve, reject) => {
            resolve(value);
        })
    }

    /**
     * 生命周期函数-更新前
     */
    [beforeUpdate](value) {
        return new Promise((resolve, reject) => {
            resolve(value);
        })
    }

    /**
     * 生命周期函数-更新后
     */
    [afterUpdate](value) {
        return new Promise((resolve, reject) => {
            resolve(value);
        })
    }

    /**
     * 生命周期函数-查询前
     */
    [beforeQuery](value) {
        return new Promise((resolve, reject) => {
            resolve(value);
        })
    }

    /**
     * 生命周期函数-查询后
     */
    [afterQuery](value) {
        return new Promise((resolve, reject) => {
            resolve(value);
        })
    }


    /**
     * 读取模型
     * @param  {[type]} name [description]
     * @return {[type]}      [description]
     */
    modules(name) {
        return M(name);
    }

    /**
     * 获取表格信息
     * @return {[type]} [description]
     */
    actionTable() {
        let FieldArray = this.modules(this.__ModelName__).tableFields();
        let TableArray = [];
        for (let index in FieldArray) {
            let item = FieldArray[index];
            if (item && is_object(item) && item.table) {
                TableArray.push({
                    "content": {
                        "label": item.label,
                        "field": index,
                    },
                    "facade": {
                        "type": item.table.type
                    }
                })
            }
        }
        TableArray.push({
            "content": {
                "label": "操作",
                "field": "action",
                "options": [{
                    "label": "编辑",
                    "action": "update"
                }, {
                    "label": "删除",
                    "action": "delete"
                }]
            },
            "facade": {
                "type": "action"
            }
        })
        //返回自动表格数据
        return {
            "name": "auto_table",
            "title": "自动生成表格",
            "type": "table",
            "content": TableArray,
            "config": {
                "handle": {
                    "delete": "handleDataDelete",
                    "update": "handleDataUpdate",
                    "pagination": "handleDataPagination"
                }
            },
            "status": 1
        };
    }

    /**
     * 获取表格操作
     * @return {[type]} [description]
     */
    actionForm() {
        let FieldArray = this.modules(this.__ModelName__).tableFields();
        let FormArray = [];
        for (let index in FieldArray) {
            let item = FieldArray[index];
            if (item && is_object(item) && item.form) {
                FormArray.push({
                    "content": {
                        "label": item.label,
                        "field": index,
                        "options": item.form.options || null,
                        "placeholder": item.form.placeholder || null
                    },
                    "facade": {
                        "type": item.form.type
                    }
                })
            }
        }
        //用于设置底部按钮字段
        FormArray.push({
            "content": {
                "label": "",
                "field": ""
            },
            "facade": {
                "type": "action",
                "options": [{
                    "label": "提交保存",
                    "type": "button",
                    "action": "submit"
                }, {
                    "label": "重置表单",
                    "type": "button",
                    "action": "reset"
                }]
            }
        })
        //返回自动表格数据
        return {
            "name": "auto_form",
            "title": "自动生成表单",
            "type": "form",
            "content": FormArray,
            "config": {
                "row": 1,
                "column": 1,
                "width": "100%",
                "label-width": "100px",
                "handle": {
                    "submit": "handleDataSubmit",
                    "reset": "handleDataReset",
                    "options": "handleLoadOptions"
                }
            },
            "status": 1
        };
    }

    async saveSetting(keyword,content) {
        return await this.modules('Setting').where({keyword}).update({content:to_json(content)});
    }

    async getSetting(keyword) {
        let data = await this.modules('Setting').where({keyword}).first();
        return to_array(data.content)
    }

    /**
     * 获取选项列表
     * @return {[type]} [description]
     */
    actionOptions() {
        return new Promise((resolve, reject) => {
            let FieldArray = this.modules(this.__ModelName__).tableFields();
            let Where = {};
            //判断是否存在
            if (FieldArray['parent_id']) {
                Where = {"parent_id": 0}
            }
            this.modules(this.__ModelName__).where(Where).select().then(data => {
                resolve(data);
            }).catch(error => {
                reject(error);
            });
        })
    }

    /**
     * 获取数据
     * @return {[type]} [description]
     */
    actionIndex() {
        return new Promise(async (resolve, reject) => {
            try {
                //前置函数
                let beforeQuery = this.lifecycleObject.Query.before;
                if (beforeQuery && typeof beforeQuery === "function") {
                    $_POST = await beforeQuery($_POST) || $_POST;
                }
                if ($_GET['page'] && $_GET['page'].size && $_GET['page'].number) {
                    let size = $_GET['page'].size;
                    let number = $_GET['page'].number;
                    this.modules(this.__ModelName__).order(['id', 'DESC']).page(number, size).select().then(async data => {
                        //执行后置方法
                        let afterQuery = this.lifecycleObject.Query.after;
                        if (afterQuery && typeof afterQuery === "function") {
                            data = await afterQuery(data) || data;
                        }
                        resolve(data);
                    }).catch(error => {
                        reject(error);
                    });
                } else {
                    this.modules(this.__ModelName__).order(['id', 'DESC']).select().then(async data => {
                        //执行后置方法
                        let afterQuery = this.lifecycleObject.Query.after;
                        if (afterQuery && typeof afterQuery === "function") {
                            data = await afterQuery(data) || data;
                        }
                        resolve(data);
                    }).catch(error => {
                        reject(error);
                    });
                }
            } catch (error) {
                reject(error);
            }

        })
    }

    /**
     * 获取单条
     * @return {[type]} [description]
     */
    actionView() {
        return new Promise((resolve, reject) => {
            let id = $_GET["id"];
            delete $_GET["id"];
            this.modules(this.__ModelName__).where({"id": id}).first().then(data => {
                resolve(data);
            }).catch(error => {
                reject(error);
            });
        })
    }

    /**
     * 删除数据
     * @return {[type]} [description]
     */
    actionDelete() {
        return new Promise(async (resolve, reject) => {
            try {
                //前置函数
                let beforeDelete = this.lifecycleObject.Delete.before;
                if (beforeDelete && typeof beforeDelete === "function") {
                    $_POST = await beforeDelete($_POST) || $_POST;
                }
                let id = $_GET["id"];
                delete $_GET["id"];
                this.modules(this.__ModelName__).where({"id": id}).delete().then(async data => {
                    //执行后置方法
                    let afterDelete = this.lifecycleObject.Delete.after;
                    if (afterDelete && typeof afterDelete === "function") {
                        data = await afterDelete(data) || data;
                    }
                    resolve(data);
                }).catch(error => {
                    reject(error);
                });
            } catch (error) {
                reject(error);
            }
        })
    }

    /**
     * 更新数据
     * @return {[type]} [description]
     */
    actionUpdate() {
        return new Promise(async (resolve, reject) => {
            try {
                //前置函数
                let beforeUpdate = this.lifecycleObject.Update.before;
                if (beforeUpdate && typeof beforeUpdate === "function") {
                    $_POST = await beforeUpdate($_POST) || $_POST;
                }
                let id = $_GET["id"] || $_POST["id"];
                if ($_POST["id"]) {
                    delete $_POST["id"];
                }
                this.modules(this.__ModelName__).where({"id": id}).validateUpdate($_POST).then(async data => {
                    //执行后置方法
                    let afterUpdate = this.lifecycleObject.Update.after;
                    if (afterUpdate && typeof afterUpdate === "function") {
                        data = await afterUpdate(data) || data;
                    }
                    resolve(data);
                }).catch(error => {
                    reject(error);
                });
            } catch (error) {
                reject(error);
            }

        })
    }

    /**
     * 创建数据
     * @return {[type]} [description]
     */
    actionCreate() {
        return new Promise(async (resolve, reject) => {
            try {
                //创建前置函数
                let beforeCreate = this.lifecycleObject.Create.before;
                if (beforeCreate && typeof beforeCreate === "function") {
                    $_POST = await beforeCreate($_POST) || $_POST;
                }
                this.modules(this.__ModelName__).validateCreate($_POST).then(async data => {
                    //执行后置方法
                    let afterCreate = this.lifecycleObject.Create.after;
                    if (afterCreate && typeof afterCreate === "function") {
                        data = await afterCreate(data) || data;
                    }
                    resolve(data);
                }).catch(error => {
                    reject(error);
                });
            } catch (error) {
                reject(error);
            }

        })
    }

    /**
     * 回收站功能
     */
    actionRecycle() {
        return new Promise((resolve, reject) => {
            if ($_GET['page'] && $_GET['page'].size && $_GET['page'].number) {
                let size = $_GET['page'].size;
                let number = $_GET['page'].number;
                this.modules(this.__ModelName__).order(['id', 'DESC']).where('deleted_time', '!=', '').page(number, size).paranoid(false).select().then(data => {
                    resolve(data);
                }).catch(error => {
                    reject(error);
                });
            } else {
                this.modules(this.__ModelName__).order(['id', 'DESC']).where('deleted_time', '!=', '').paranoid(false).select().then(data => {
                    resolve(data);
                }).catch(error => {
                    reject(error);
                });
            }
        })
    }

    /**
     * 彻底删除
     * @return {[type]} [description]
     */
    actionDestroy() {
        return new Promise((resolve, reject) => {
            let id = $_GET["id"];
            delete $_GET["id"];
            this.modules(this.__ModelName__).where({"id": id}).destroy().then(data => {
                resolve(data);
            }).catch(error => {
                reject(error);
            });
        })
    }

    /**
     * 数据恢复功能
     * @return {[type]} [description]
     */
    actionRecover() {
        return new Promise((resolve, reject) => {
            let id = $_GET["id"];
            delete $_GET["id"];
            this.modules(this.__ModelName__).where({"id": id}).restore().then(data => {
                resolve(data);
            }).catch(error => {
                reject(error);
            });
        })
    }
}

